<template>
  <a-select
    :show-search="true"
    :show-arrow="true"
    :allow-clear="true"

    :value="seletedOption"
    placeholder="请输入姓名或首字母"
    :filter-option="false"
    :not-found-content="null"
    @search="handleSearch"
    @change="handleChange"
  >
    <a-select-option v-for="d in data" :key="d.value">
      {{ d.text }}
    </a-select-option>
  </a-select>
</template>

<script>
  import { mapGetters } from 'vuex';
  import { httpAction, getAction } from '@/api/manage';

  export default {
    name:"JUserSelect",
    props: ["value"],
    model: {
      prop: 'value',
      event: 'change'
    },
    data() {
      return {
        data: [],
        seletedOption: undefined,
        url:"/villageCadreAssist/vcaResident/queryTopN"
      };
    },
    computed:{
      ...mapGetters(["userInfo"])
    },
    methods: {
      handleSearch(value) {
        this.data.splice(0,this.data.length);
        // this.data.push({
        //   text:value,
        //   value:-1
        // });
        if(value.length>=2){
          getAction(this.url,{firstLetter:value}).then((res) => {
            if (res.success) {
              if(res.result){
                let departName = this.userInfo["orgCodeTxt"];
                res.result.forEach(i=>{
                  let address = i["hostAddress"];
                  address = address.substring(departName.length).replace(":","");
                  var arr = res.result;
                  for(let item=0;item<arr.length;item++){
                    if(i["id"]!=arr[item]["id"] && arr[item]["hostAddress"]==i["hostAddress"] && arr[item]["residentName"]==i["residentName"]){
                      address += i["idcard"].substring(6,10);
                      break;
                    }
                  }
                  this.data.push({
                    text:i["residentName"]+(address?" ("+address+")":""),
                    value:i["id"]
                  });
                });
              }
              // console.log('res.result',res.result)
            }else{
              this.$message.warning(res.message);
            }
          });
        }
      },
      handleChange(value) {
          this.seletedOption = value
          if(!value){
            this.$emit('change', '');
            this.seletedOption = null
          } else if (value instanceof Array) {
            this.$emit('change', value.map(item => item.value).join(','))
          } else if(value instanceof Object){
            this.$emit('change', value.value,value.label)
          } else {
            this.$emit('change', value)
          }
      }
    },
  };
</script>
